package com.monitor.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.monitor.dao.ContactDao;
import com.monitor.po.Contact;
import com.monitor.util.Pager;

@SuppressWarnings("unchecked")
public class ContactDaoImpl implements ContactDao {
	private SessionFactory sessionFactory;

	@Override
	public Pager<Contact> getContactByUid(long uid, int pageSize, int currentPage) throws Exception {
		try {
			Session sesion = this.sessionFactory.getCurrentSession();
			Query query = sesion.createQuery("select count(*) from Contact c where c.ownerUid=:ownerUid").setLong("ownerUid", uid);
			int totalCount = ((Number) query.uniqueResult()).intValue();
			int pageCount = (totalCount % pageSize == 0) ? totalCount / pageSize : (totalCount / pageSize) + 1;
			List<Contact> list = sesion.createQuery("from Contact c where c.ownerUid=:ownerUid order by c.addTimestamp desc").setLong("ownerUid", uid).setFirstResult((currentPage - 1) * pageSize)
					.setMaxResults(pageSize).list();
			Pager<Contact> pager = new Pager<Contact>(list, currentPage, totalCount, pageCount);
			return pager;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting getContactByUid()....");
		}
	}

	@Override
	public boolean addContact(long uid, List<Contact> contacts) throws Exception {
		if (contacts == null || contacts.isEmpty()) {
			return false;
		}
		try {
			StringBuffer sqlBuffer = new StringBuffer("insert ignore into monitor_contact(id,name,phone,ownerUid,addTime,addTimestamp) values ");
			int size = contacts.size();
			for (int i = 0; i < size; i++) {
				sqlBuffer.append("(?,?,?,?,?,?)");
				if (i != size - 1) {
					sqlBuffer.append(",");
				}
			}
			SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sqlBuffer.toString());
			for (int i = 0; i < size; i++) {
				Contact c = contacts.get(i);
				String number = c.getPhone();
				query.setString(6 * i + 0, uid + number);
				query.setString(6 * i + 1, c.getName());
				query.setString(6 * i + 2, number);
				query.setLong(6 * i + 3, uid);
				query.setDate(6 * i + 4, new Date());
				query.setLong(6 * i + 5, System.currentTimeMillis());
			}
			query.executeUpdate();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("addContact发生异常");
		}
	}

	@Override
	public int deleteContactByUid(long uid) throws Exception {
		try {
			return sessionFactory.getCurrentSession().createQuery("delete from Contact c where c.ownerUid=:ownerUid").setLong("ownerUid", uid).executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting deleteContactByUid()....");
		}
	}

	@Override
	public int deleteContact(long uid, String cid) throws Exception {
		try {
			return sessionFactory.getCurrentSession().createQuery("delete from Contact c where c.id =:id and c.ownerUid=:ownerUid").setString("id", cid).setLong("ownerUid", uid).executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting deleteContact()....");
		}
	}

	@Override
	public int deleteContact(long uid, String[] phones) throws Exception {
		try {
			StringBuffer sql = new StringBuffer("delete from Contact c where c.ownerUid=? and (");
			int length = phones.length;
			for (int i = 0; i < length; i++) {
				sql.append(" c.phone=? ");
				if (i != length - 1) {
					sql.append(" or ");
				}
			}
			sql.append(")");
			Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());
			query.setLong(0, uid);
			for (int i = 0; i < length; i++) {
				String phone = phones[i];
				query.setString(i + 1, phone);
			}
			return query.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting deleteContact()....");
		}
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
